#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* newTree(vector<int>& preorder, vector<int>& inorder, int& preI, int Inleft, int Inright)
    {
        if (Inleft > Inright)
            return nullptr;

        int _begin = Inleft;

        TreeNode* node = new TreeNode(preorder[preI]);
        while (Inleft <= Inright && inorder[Inleft] != preorder[preI])
        {
            Inleft++;
        }
        preI++;

        node->left = newTree(preorder, inorder, preI, _begin, Inleft - 1);
        node->right = newTree(preorder, inorder, preI, Inleft + 1, Inright);

        return node;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int i = 0;
        return newTree(preorder, inorder, i, 0, inorder.size() - 1);
    }
};